package com.tools.payhelper.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * TODO:
 *
 * @author hm
 * @date 2018/4/23
 * @copyright
 */
public class FileModifyUtils {

    /**
     * 替换文本内容
     * @param filePath
     * @param oldstr
     * @param newStr
     * @return
     */
    public static boolean autoReplace(String filePath, String oldstr, String newStr) {
        File file=new File(filePath);
        Long fileLength=file.length();
        byte[] fileContext=new byte[fileLength.intValue()];
        try{
            FileInputStream in=new FileInputStream(filePath);
            in.read(fileContext);
            in.close();
            String str = new String(fileContext);

            str = str.replace(oldstr,newStr);
            PrintWriter out=new PrintWriter(filePath);
            out.write(str.toCharArray());
            out.flush();
            out.close();

        }catch (IOException e){
            e.printStackTrace();
            return false;
        }

        return true;
    }
    public static String getConfigAdd(String filePath, String containsStr){
        String add = null;
        File file = new File(filePath);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            //一次读一行，读入null时文件结束
            while ((tempString = reader.readLine()) != null) {
                if (tempString.startsWith(containsStr)){
                    add = tempString.substring(containsStr.length());
                    return add;
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return add;
    }

}
